/*
 * FNISVGEditor - JavaScript - based editor for SVG graphics 
 * Copyright (C) 2008 - 2009 Antti Leppä / Foyt
 * http://www.foyt.fi
 * 
 * License: 
 * 
 * Licensed under GNU Lesser General Public License Version 2.1 or later (the "LGPL") 
 * http://www.gnu.org/licenses/lgpl.html
 */
FNISVGEditorPluginManager = Class.create({
  initialize : function(editorInstance) {
    this._editorInstance = editorInstance;
    this._pluginsPath = this._editorInstance.getBasePath() + '/plugins/';
    this._customPluginPath = this._editorInstance.getComponentOptions().customPluginPath;
    this._loadingPlugins = new Array();
  },
  loadPlugins : function(plugins) {
    for ( var i = 0; i < plugins.length; i++)
      this._loadingPlugins.push(plugins[i]);

    for ( var i = this._loadingPlugins.length - 1; i >= 0; i--) {
      this._loadPlugin(this._loadingPlugins[i]);
    }
  },
  _loadPlugin : function(pluginName) {
    var pluginURL = pluginName.toLowerCase();
    var _this = this;
    var loadMode = this._editorInstance.getConfigurationManager().getValue("loadMode");

    if (this._customPluginPath) {
      FNISVGPluginLoader.load(pluginName, this._customPluginPath + '/' + pluginURL, loadMode, function(pluginName, pluginClass) {
        _this._initializePlugin(pluginClass, FNISVGPluginLoader.getURL(pluginName));
      }, function() {
        FNISVGPluginLoader.load(pluginName, _this._pluginsPath + pluginURL, loadMode, function(pluginName, pluginClass) {
          _this._initializePlugin(pluginClass, FNISVGPluginLoader.getURL(pluginName));
        }, function() {
          alert("Error while loading: " + pluginName);
        });
      });

    } else {
      FNISVGPluginLoader.load(pluginName, this._pluginsPath + pluginURL, loadMode, function(pluginName, pluginClass) {
        _this._initializePlugin(pluginClass, FNISVGPluginLoader.getURL(pluginName));
      }, function() {
        alert("Error while loading: " + pluginName);
      });
    }
  },
  _initializePlugin : function(pluginClass, url) {
    var plugin = new pluginClass(this._editorInstance, url);

    for ( var i = 0; i < this._loadingPlugins.length; i++)
      if (this._loadingPlugins[i] == plugin.getName())
        this._loadingPlugins.splice(i, 1);

    if (this._loadingPlugins.length == 0) {
      this.fire("pluginsLoaded", {});
    }
  }
});

Object.extend(FNISVGEditorPluginManager.prototype, fni.events.FNIEventSupport);
